﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.checkstock
{
    public partial class checkstockbill_add : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "";

        private void Reset()
        {
            uc_from_warehouse.Reset();
            txt_remark.Text = "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ;
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            edowork.com.Model.check_stockInfo check_stockInfo = new check_stockInfo();
            edowork.com.Model.check_stock_detailInfo check_stock_detailInfo = new check_stock_detailInfo();

            check_stockInfo.Areaid = "";
            check_stockInfo.Billdate = uc_from_dates.getValue();
            check_stockInfo.Billtype = "1005";
            check_stockInfo.Checkdate = "";
            check_stockInfo.Checkremark = "";
            check_stockInfo.Checkstu = "0";
            check_stockInfo.Checkuserid = "";
            check_stockInfo.M_date = "";
            check_stockInfo.M_ID = "";
            check_stockInfo.M_stu = "0";
            check_stockInfo.Remark = txt_remark.Text.Trim();
            check_stockInfo.StaffID = "";
            check_stockInfo.Staffremark = "";
            check_stockInfo.Staffstu = "0";
            check_stockInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");
            check_stockInfo.Warehouseid = uc_from_warehouse.getValue();
            check_stockInfo.Userid = Session["userid"].ToString();

            if (String.IsNullOrEmpty(check_stockInfo.Billdate))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入开单日期");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(check_stockInfo.Warehouseid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择盘点仓库");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }


            //取得销售出库单编码
            check_stockInfo.Csid = SysID.SCR_CSID(Session["connectionString"].ToString(), ref alert_msg);

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "", error_msg="";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(check_stockInfo.Billdate).ToString("yyyy"), DateTime.Parse(check_stockInfo.Billdate).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //检查是否存在盘点单
                sql = String.Format("select csid from check_stock where warehouseid='{0}' and checkstu='0'", check_stockInfo.Warehouseid);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前仓库正在盘点，不能进行出入库操作。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //调用存储过程锁定资源表
                sql = String.Format("exec sys_checkstock_locktable");

                dsResult = exec.ExecStoreProcQueryDataSet(sql, ref error_msg, tran);

                if (dsResult == null)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, error_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //写入盘点单主表信息
                sql = String.Format(check_stockInfo.SQL_Insert(), check_stockInfo.Csid, check_stockInfo.Billdate, check_stockInfo.Billtype, check_stockInfo.Remark, check_stockInfo.Warehouseid, check_stockInfo.Areaid, check_stockInfo.Userid, check_stockInfo.Sysdate,
                                                                  check_stockInfo.StaffID, check_stockInfo.Staffstu, check_stockInfo.Staffremark, check_stockInfo.Checkuserid, check_stockInfo.Checkdate, check_stockInfo.Checkstu, check_stockInfo.Checkremark,
                                                                  check_stockInfo.M_stu, check_stockInfo.M_date, check_stockInfo.M_ID);


                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //写入盘点单明细信息
                sql = @"insert into check_stock_detail(csid, storageid, productcode, Qty1, Qty2)
                          select a.csid, b.storageid, b.productcode, b.qty1, 0
                            from check_stock a, inventory b
                              where a.csid = '{0}'
                                and a.warehouseid=b.warehouseid";

                sql = String.Format(sql, check_stockInfo.Csid);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            Reset();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //重置
        protected void btnReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string url = "/system/checkstock/checkstockbill.aspx";

            Response.Redirect(url);
        }
    }
}